<?php

/**
 * 优质口碑内容-短标题
 * 每天4点10分跑一次数据，更新话题关联点wiki数据
 *
 **/


ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';


use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\ObjRelateWiki;
use Doraemon\model\Article;
use Doraemon\model\Blank;
use Doraemon\model\Guide;
use Doraemon\model\Photos;
use Doraemon\service\User;
use Doraemon\tools\BlockType;
use Doraemon\tools\Log;
use Biz\cache\wiki\ShortTitle;
use Doraemon\model\Member;

$start = time();
$page = 1;
$pageSize = 100;
$list = [];
try {
    
    do {
        $limit = [($page - 1) * $pageSize, $pageSize];
        $limit = implode(',', $limit);
        $sql = "SELECT  brand_name,brand_alias,obj_id,wiki_id, brand_id,obj_type  FROM wiki LEFT JOIN obj_relate_wiki as relate
    ON wiki.id = relate.wiki_id left join brand on brand.id = wiki.brand_id where wiki.status = 2 and brand_id > 0 and obj_type > 0 and is_test = 0  limit " . $limit;
        //获取品牌名称
        
        $list = ObjRelateWiki::query($sql)->fetchAll();
        $note = []; //photo 表
        $article = []; //article 表
        $blank = []; //blank 表
        $guide = [];   //guide 表
        foreach ($list as $key => $v) {
            $brand_name = (!empty($v['brand_alias'])) ? array_merge([$v['brand_name']],
                json_decode($v['brand_alias'], true)) : [$v['brand_name']];
            $tag = [
                'wiki_id' => $v['wiki_id'],
                'brand_name' => $brand_name,
                'obj_id' => $v['obj_id'],
                'obj_type' => $v['obj_type'],
                'brand_id' => $v['brand_id'],
            ];
            //obj_type 1:note  2:文章   3:整屋   4:指南
            switch ($v['obj_type']) {
                case 1:
                    $note[] = $tag;
                    break;
                case 2:
                    $blank[] = $tag;
                    break;
                case 3:
                    $article[] = $tag;
                    break;
                case 4:
                    $guide[] = $tag;
                    break;
            }
        }
        setBlankTitle($blank);
        setNoteTitle($note);
        setGuideTitle($guide);
        setArticleTitle($article);
        $page++;
    } while ($list);
    $end = time();
} catch (\Exception $e) {
    $params = [
        'blank' => $blank,
        'note' => $note,
        'guide' => $guide,
        'article' => $article,
    ];
    Log::info("优质口碑内容", date('Y-m-d-H-i-s') . "优质口碑内容-错误信息：" . $e->getMessage() . "执行数据:" . json_encode($params));
    var_dump("优质口碑内容", date('Y-m-d-H-i-s') . "优质口碑内容-错误信息：" . $e->getMessage() . "执行数据:" . json_encode($params));
}
var_dump(date('Y-m-d-H-i-s') . '存储优质口碑内容完成，总耗时:' . ($end - $start) . '秒，' . (($end - $start) / 60) . '分');

/**
 * 存储文章优质口碑内容展示
 * @param $params
 */
function setBlankTitle($params)
{
    $data = formatData($params);
    if ($data) {
        //存储到缓存
        foreach ($data as $wiki_id => $v) {
            if ($v) {
                $ids = $v['obj_ids'];
                $titles = Blank::select(['title', 'bid(id)', 'uid', 'admin_score'],
                    ['bid' => $ids, 'title[!]' => ' ', 'status' => 1, 'ORDER' => ['admin_score' => 'DESC']]);
                if ($titles) {
                    setRedisContent($wiki_id, $v, $titles);
                }
            }
        }
    }
}

/**
 * 存储 note 优质口碑内容展示
 * @param $params
 */
function setNoteTitle($params)
{
    $data = formatData($params);
    if ($data) {
        //存储到缓存
        foreach ($data as $wiki_id => $v) {
            if ($v) {
                $ids = $v['obj_ids'];
                $titles = Photos::select(['title', 'id', 'uid'],
                    ['id' => $ids, 'title[!]' => '', 'status' => 1, 'ORDER' => ['admin_score' => 'DESC']]);
                if ($titles) {
                    setRedisContent($wiki_id, $v, $titles);
                }
            }
        }
    }
}

/**
 * 存储 整屋 优质口碑内容展示
 * @param $params
 */
function setArticleTitle($params)
{
    $data = formatData($params);
    if ($data) {
        //存储到缓存
        foreach ($data as $wiki_id => $v) {
            if ($v) {
                $ids = $v['obj_ids'];
                $titles = Article::select(['title', 'aid(id)', 'uid'],
                    ['aid' => $ids, 'title[!]' => '', 'status' => 1, 'ORDER' => ['admin_score' => 'DESC']]);
                if ($titles) {
                    setRedisContent($wiki_id, $v, $titles);
                }
            }
        }
    }
}

/**
 * 存储 指南 优质口碑内容展示
 * @param $params
 */
function setGuideTitle($params)
{
    $data = formatData($params);
    if ($data) {
        //存储到缓存
        foreach ($data as $wiki_id => $v) {
            if ($v) {
                $ids = $v['obj_ids'];
                $titles = Guide::select(['title', 'id', 'uid'], ['id' => $ids, 'status' => 1, 'title[!]' => '']);
                if ($titles) {
                    setRedisContent($wiki_id, $v, $titles);
                }
            }
        }
    }
}

/**
 * 格式化话数据 以wiki_id 作为key
 * @param $params
 * @return array
 */
function formatData($params)
{
    $new = [];
    $id = [];
    if ($params) {
        foreach ($params as $key => $param) {
            $new[$param['wiki_id']] = [
                'brand_name' => $param['brand_name'],
                'obj_type' => $param['obj_type'],
//                'obj_id' => $param['obj_id'],
            ];
            $id[] = $param['obj_id'];
            $new[$param['wiki_id']]['obj_ids'] = $id;
        }
    }
    return $new;
}

/**
 * 存入缓存
 * @param $wiki_id
 * @param $v
 * @param $titles
 */
function setRedisContent($wiki_id, $v, $titles)
{
    foreach ($v['brand_name'] as $brand_title) {
        foreach ($titles as $val) {
            if (!$val) {
                continue;
            }
            $title = trim($val['title']);
            if (mb_strpos($title, $brand_title) !== false) {
                //获取首次出现位置
                $start_point = mb_strpos($title, $brand_title);
                //计算品牌标题长度
                $brand_title_len = mb_strlen($brand_title);
                $end_point  = $start_point +  $brand_title_len;
                $start = ($start_point - 8 < 0) ? 0 : $start_point - 8;
                $len = ($end_point + 8 > mb_strlen($title)) ? mb_strlen($title) : $end_point + 8;
                $short = mb_substr($title, $start, $len);
                $uid = $val['uid'];
                $avatar_imgs = getUserIcon($uid);
                //obj_type 1:note  2:文章   3:整屋   4:指南
                $type = '';
                switch ($v['obj_type']) {
                    case 1:
                        $type = BlockType::TYPE_PHOTO;
                        break;
                    case 2:
                        $type = BlockType::TYPE_BLANK;
                        break;
                    case 3:
                        $type = BlockType::TYPE_ARTICLE;
                        break;
                    case 4:
                        $type = BlockType::TYPE_GUIDE;
                        break;
                }
                if (empty($type)) {
                    continue;
                }
                $data[$wiki_id] = [
                    'title' => $short,
                    'obj_id' => $val['id'],
                    'obj_type' => $type,
                    'wiki_id' => $wiki_id,
                    'pic' => $avatar_imgs,
                ];
                var_dump($data);
                ShortTitle::setShortTitleById($data);
                break 2;
            }
        }
        
    }
    
}

/**
 * 获取用户头像
 * @param $uid
 * @return string
 */
function getUserIcon($uid)
{
    $where = [
        "status" => [
            Member::STATUS_NORMAL,
            Member::STATUS_NEW
        ],
        "uid" => $uid,
    ];
    $field = ['uid', 'avatar_version'];
    $user_info = Member::getUserInfoByid($field, $where);
    if ($user_info) {
        $avatar_imgs = User::getUserAvatarPicUrl($user_info['uid'], $user_info['avatar_version']);
    }
    return $avatar_imgs[0] ?? '';
}

